/*
 * This file contains basic utility classes and function.
 */

// Extend built in Math functionality
// Clamp value to interval
function Clamp(x, min, max) {
    if (x < min)
        return min;
    if (x > max)
        return max;
    return x;
}
;

// Get click coordinates of canvas
HTMLCanvasElement.prototype.getMouseEventCoords = function (event) {
    var totalOffsetX = 0;
    var totalOffsetY = 0;
    var canvasX = 0;
    var canvasY = 0;
    var currentElement = this;

    do {
        totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
        totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
        currentElement = currentElement.offsetParent;
    }
    while (currentElement);

    // correct coords with document scroll offset
    canvasX = event.pageX - totalOffsetX - window.pageXOffset;
    canvasY = event.pageY - totalOffsetY - window.pageYOffset;

    return {x: canvasX, y: canvasY};
};

// Extend built in Array functionality
// Remove element from the list (involves search)
Array.prototype.remove = function(e) {
    var idx = this.indexOf(e);
    if (idx !== -1) {
        this.splice(idx, 1);
    }
    return idx;
};
// Extend built in Array functionality
// Pop elements from this array until it is empty, and while doing so, call 'fun' 
// with each of the elements.
Array.prototype.concurrentCallAllAndClear = function(fun) {
    while (this.length > 0) {
        fun(this.pop());
    }
};
